package com.yxy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yxy.common.PageResult;
import com.yxy.constant.StatusConstant;
import com.yxy.domain.dto.BannerDTO;
import com.yxy.domain.dto.BannerPageQueryDTO;
import com.yxy.domain.po.Banner;
import com.yxy.domain.vo.BannerPageQueryVO;
import com.yxy.domain.vo.BannerVO;
import com.yxy.mapper.BannerMapper;
import com.yxy.service.BannerService;
import com.yxy.utils.QiniuOSSUtil;
import com.yxy.utils.SplitUtil;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BannerServiceImpl implements BannerService {

    private final BannerMapper bannerMapper;
    public BannerServiceImpl(BannerMapper bannerMapper){
        this.bannerMapper = bannerMapper;
    }

    /**
     * 添加轮播图
     * @param bannerDTO
     */
    @Override
    public void add(BannerDTO bannerDTO) {
        Banner banner = null;
        for (String url : bannerDTO.getBannerList()) {
            banner = new Banner();
            banner.setUrl(url);
            banner.setStatus(StatusConstant.ENABLE);
            bannerMapper.add(banner);
        }
    }

    /**
     * 获取轮播图（用户端）
     * @return
     */
    @Override
    public List<BannerVO> list() {
        List<Banner> bannerList = bannerMapper.selectAll();
        List<BannerVO> vo = BeanUtil.copyToList(bannerList, BannerVO.class);
        return vo;
    }

    /**
     * 分页查询
     * @param bannerPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(BannerPageQueryDTO bannerPageQueryDTO) {
        PageHelper.startPage(bannerPageQueryDTO.getPage(), bannerPageQueryDTO.getPageSize());
        Page<BannerPageQueryVO> page = bannerMapper.page(bannerPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 删除
     * @param id
     * @param bannerVO
     */
    @Override
    public void delete(int id, String url) {
        bannerMapper.deleteById(id);
        // 从七牛云删除文件
        QiniuOSSUtil.deleteFileFromQiniu("sports/" + SplitUtil.split(url));
    }

    /**
     * 修改状态
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(int id, int status) {
        bannerMapper.updateStatus(id, status);
    }
}
